﻿using System;
using System.Linq;
using CsharpTool.SignalRServer;
using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.SignalR;

namespace Microsoft.Extensions.DependencyInjection
{
    /// <summary>
    /// signalr扩展
    /// </summary>
    public static class ServiceCollectionExtensions
    {
        /// <summary>
        /// 添加signalr服务,app.MapHub{SignalRHub}必须使用<see cref="SignalRHub"/>类
        /// </summary>
        public static SignalRBuilder AddSignalRHub(this IServiceCollection services, Action<HubOptions>? conf = null, Action<NewtonsoftJsonHubProtocolOptions>? serializeConfig = null)
        {
            if (conf != null)
                services.Configure(conf);
            services.AddSingleton<IMessageSend, MessageSend>();
            var srsBuilder = services.AddSignalR(); 
            if (serializeConfig != null)
                srsBuilder.AddNewtonsoftJsonProtocol(serializeConfig);
            else
                srsBuilder.AddNewtonsoftJsonProtocol();
            return new SignalRBuilder(services);
        }

        /// <summary>
        /// 添加signalr服务
        /// </summary>
        public static SignalRBuilder AddSignalRHub<THub, TClient, TReceiveData>(this IServiceCollection services, Action<HubOptions>? conf = null, Action<NewtonsoftJsonHubProtocolOptions>? serializeConfig = null) where TClient : class, ISignalRHubClient where THub : Hub<TClient> ,ISignalRHub<TClient, TReceiveData>
        {
            if (conf != null)
                services.Configure(conf);
            services.AddSingleton<IMessageSend, MessageSend<THub, TClient, TReceiveData>>();
            var srsBuilder = services.AddSignalR();
            if (serializeConfig != null)
                srsBuilder.AddNewtonsoftJsonProtocol(serializeConfig);
            else
                srsBuilder.AddNewtonsoftJsonProtocol();
            return new SignalRBuilder(services);
        }

        /// <summary>
        /// 添加signalr数据接收处理器
        /// </summary>
        public static void AddSignalRReceiveHandler<TRecevieHandler, TReceiveData>(this SignalRBuilder builder) where TRecevieHandler : class, IMessageReceive<TReceiveData>
        { 
            builder.Services.AddSingleton<IMessageReceive<TReceiveData>, TRecevieHandler>();
        }
    }
}
